package com.pingan.haofang.searchcloud.monitor.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.persistence.EntityManager;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.pingan.haofang.gov.sm.account.common.SessionVisitor;
import com.pingan.haofang.gov.sm.account.common.UserThreadContext;
import com.pingan.haofang.searchcloud.common.constants.Status;
import com.pingan.haofang.searchcloud.common.dto.OperationResult;
import com.pingan.haofang.searchcloud.common.dto.PageDTO;
import com.pingan.haofang.searchcloud.common.utils.DateUtils;
import com.pingan.haofang.searchcloud.index.domain.Index;
import com.pingan.haofang.searchcloud.index.service.IndexService;
import com.pingan.haofang.searchcloud.monitor.constants.WarningType;
import com.pingan.haofang.searchcloud.monitor.dao.DashboardWarningConfigDao;
import com.pingan.haofang.searchcloud.monitor.dao.DashboardWarningHistoryDao;
import com.pingan.haofang.searchcloud.monitor.domain.DashboardWarningConfig;
import com.pingan.haofang.searchcloud.monitor.dto.WarningConfigDTO;
import com.pingan.haofang.searchcloud.monitor.dto.WarningHistoryCountDTO;
import com.pingan.haofang.searchcloud.monitor.dto.WarningViewQueryDTO;
import com.pingan.haofang.searchcloud.monitor.dto.WarningViewQueryResult;
import com.pingan.haofang.searchcloud.monitor.service.DashboardWarningConfigService;
import com.pingan.haofang.searchcloud.user.dto.SearchProjectDto;
import com.pingan.haofang.searchcloud.user.service.SearchProjectService;

/**
 * 搜索云预警配置
 *
 * @author EX-ZHOUYONG005
 * @date 2018/10/19
 * @since 1.0.0
 */
@Service
public class DashboardWarningConfigServiceImpl implements DashboardWarningConfigService {

    @Autowired
    private DashboardWarningConfigDao dashboardWarningConfigDao;

    @Autowired
    private DashboardWarningHistoryDao dashboardWarningHistoryDao;

    @Resource
    private EntityManager entityManager;

    @Autowired
    private SearchProjectService searchProjectService;

    @Autowired
    private IndexService indexService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OperationResult deleteWarningConfig(Long id) {
        DashboardWarningConfig config = dashboardWarningConfigDao.findOne(id);
        if (config != null && config.getStatus() == Status.NORMAL.getValue()) {
            config.setStatus(Status.STOP.getValue());
            SessionVisitor visitor = UserThreadContext.getSessionVisitor();
            if (visitor != null) {
                long userId = visitor.getAccountId();
                config.setUpdateBy(userId);
            }
            dashboardWarningConfigDao.save(config);
            return OperationResult.of(true, "");
        }
        return OperationResult.of(false, "此配置不存在");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OperationResult warningConfigNew(WarningConfigDTO dto) {
        int warningType = dto.getWarningType();
        DashboardWarningConfig config = new DashboardWarningConfig();

        if (warningType != WarningType.RESOURCE.getValue()) {
            String indexIdsStr = dto.getIndexIds();
            //全部
            if (StringUtils.isBlank(indexIdsStr) || "-1".equals(indexIdsStr)) {
                config.setIndexId("-1");
                config.setIndexName("all");
            } else {
                config.setIndexId(indexIdsStr);
                String[] strs = indexIdsStr.split(",");
                final List<Long> indexIds = Arrays.stream(strs).map(x -> Long.parseLong(x)).collect(Collectors.toList());
                List<Index> indices = indexService.getByindexIds(indexIds);
                Map<Long, String> map = indices.stream().collect(Collectors.toMap(Index::getId, Index::getIndexName));
                List<String> names = indexIds.stream().map(x -> map.get(x)).collect(Collectors.toList());
                String nameStr = StringUtils.join(names, ",");
                config.setIndexName(nameStr);
            }

            Long projectId = dto.getProjectId();
            if (projectId != null) {
                config.setProjectId(dto.getProjectId());
                SearchProjectDto searchProjectDto = searchProjectService.get(dto.getProjectId());
                if (searchProjectDto != null) {
                    config.setProjectName(searchProjectDto.getProjectName());
                }
            }
        }

        config.setWarningType(warningType);
        config.setWarningConfig(dto.getWarningConfig());
        config.setMailTo(dto.getMailTo());

        SessionVisitor visitor = UserThreadContext.getSessionVisitor();
        if (visitor != null) {
        	long userId = visitor.getAccountId();
            config.setCreateBy(userId);
            config.setUpdateBy(userId);
        }
        config.setStatus(Status.NORMAL.getValue());

        dashboardWarningConfigDao.save(config);
        return OperationResult.of(true, "");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PageDTO<WarningViewQueryResult> queryWarningView(WarningViewQueryDTO dto) {
        // 根据项目，索引，预警人查询预警配置
        List<WarningViewQueryResult> queryList = dashboardWarningConfigDao.queryWarningView(dto, entityManager);
        if (CollectionUtils.isEmpty(queryList)) {
            return PageDTO.builder(new ArrayList<WarningViewQueryResult>(0)).build();
        }

        List<Long> configIds = queryList.stream().map(x -> x.getId()).collect(Collectors.toList());

        // 获取所有满足条件的配置ID
        List<WarningHistoryCountDTO> historyDateDTOS =
                dashboardWarningHistoryDao.countByConfigId(configIds, entityManager);

        // <配置id,最近预警时间>
        Map<Long, Date> dateMap =
                historyDateDTOS.stream().collect(Collectors.toMap(x -> x.getConfigId(), x -> x.getDate()));

        for (WarningViewQueryResult config : queryList) {
            Long configId = config.getId();
            Date date = dateMap.get(configId);
            if (date != null) {
                config.setWaringTime(DateUtils.formatDate(date));
            }
        }

        int total = dashboardWarningConfigDao.queryWarningCount(dto, entityManager);
        int pageSize = dto.getPageSize();
        int pageNo = dto.getPageNo();
        int totalPages = (total % pageSize == 0) ? total / pageSize : total / pageSize + 1;

        PageDTO<WarningViewQueryResult> page = PageDTO.builder(queryList).totalPages(totalPages).totalRecords(total)
                .pageNo(pageNo).pageSize(pageSize).build();
        return page;
    }

    @Override
    public List<DashboardWarningConfig> findByWarningTypeAndStatus(int warningType) {
        return dashboardWarningConfigDao.findByWarningTypeAndStatus(warningType, Status.NORMAL.getValue());
    }
}
